package com.example.demo.lock;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

@SuppressWarnings("AlibabaAvoidManuallyCreateThread")
public class OptimisticLockDemo {
    public AtomicInteger atomicCount = new AtomicInteger();
    public Integer commonCount = 0;

    public void atomicInc(){
        try{
            Thread.sleep(1); //延迟 1 毫秒
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        atomicCount.getAndIncrement();
    }
    public void commonInc(){
        try{
            Thread.sleep(1); //延迟 1 毫秒，为了看清楚并发问题
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        commonCount = commonCount + 1;
    }

    public static void main(String[] args) throws InterruptedException {

        OptimisticLockDemo demo = new OptimisticLockDemo();

        //有锁 case
        final CountDownLatch latch1 = new CountDownLatch(100);
        for(int i=0;i<100;i++){
            new Thread(() -> {
                demo.atomicInc();
                latch1.countDown();
            }).start();
        }
        latch1.await();
        System.out.println("atomicCount 运行结果(确定为 100)："+demo.atomicCount);

        //无锁 case
        final CountDownLatch latch2 = new CountDownLatch(100);
        for(int i=0;i<100;i++){
            new Thread(() -> {
                demo.commonInc();
                latch2.countDown();
            }).start();
        }
        latch2.await();
        System.out.println("commonCount 运行结果(不确定)："+demo.commonCount);
    }
}
